package com.itheima.service.impl;

import com.itheima.entity.BeanConv;
import com.itheima.pojo.Role;
import com.itheima.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.vo.MenuAndRoleVo;
import com.itheima.vo.MenuVo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {


//    @Override
//    public Object getMenus() {
//        return null;
//    }

    @Override
    public List<MenuVo> getMenus(String username) {
        List<Menu> menuList = baseMapper.getMenus(username);
        List<MenuVo> menuVoList = new ArrayList<>();
//        List<Menu> children = new ArrayList<>();
        for (Menu menu : menuList) {
            if (!menu.getPath().contains("-")) {
                menuVoList.add(BeanConv.toBean(menu, MenuVo.class));
            }
        }
        menuVoList.stream().forEach(menuVo -> {
            menuVo.setChildren(new ArrayList<Menu>());
        });
        for (Menu menu : menuList) {
            if (menu.getPath().contains("-")) {
                String index = menu.getPath().split("-")[0];
                for (MenuVo menuVo : menuVoList) {

                    if (index.equals(menuVo.getPath())||Integer.parseInt(index)==Integer.parseInt(menuVo.getPath())||index==menuVo.getPath()) {
                        menuVo.getChildren().add(menu);
                    }
                }
            }
        }
        return menuVoList;
    }

    @Override
    public List<Long> getRoleByMenuId(long id) {
        return baseMapper.getRoleByMenuId(id);
    }

    @Override
    public List<Role> getRole() {
        return baseMapper.getRole();
    }

    @Override
    public void updateRoles(MenuAndRoleVo menuAndRoleVo) {
        Long menuId =Long.parseLong(menuAndRoleVo.getMenuId()) ;
        String[] roleIdStrs = menuAndRoleVo.getRoleIds();
        Long[] roleIds = new Long[roleIdStrs.length];
        for (int i = 0; i < roleIdStrs.length; i++) {
            roleIds[i] = Long.parseLong(roleIdStrs[i]);
        }
        baseMapper.deleteByMenuId(menuId);
        for (Long roleId : roleIds) {
            baseMapper.addMenuAndRole(menuId,roleId);
        }
    }
}